package com.infore.exchange.main.utils;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cloudera.api.ApiRootResource;
import com.cloudera.api.ApiUtils;
import com.cloudera.api.ClouderaManagerClientBuilder;
import com.cloudera.api.DataView;
import com.cloudera.api.model.ApiHost;
import com.cloudera.api.model.ApiTimeSeriesRequest;
import com.cloudera.api.v11.TimeSeriesResourceV11;
import com.cloudera.api.v30.HostsResourceV30;
import com.cloudera.api.v33.RootResourceV33;
import com.infore.common.model.dto.TimeSeriesDto;

import javax.ws.rs.core.Response;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ClouderaManagerUtils {
    private static String cdhApiPath = "10.87.229.25";
    private static String cdhApiPort = "7180";
    private static String cdhApiUserName = "admin";
    private static String cdhApiPassword = "admin";

    /**
     * tsquery
     * @param query
     * @param fromDate
     * @param toDate
     * @return
     * @throws ParseException
     */
    public static List<TimeSeriesDto> getTimeSeriesResponse(String query, Date fromDate, Date toDate) throws ParseException {
        List<TimeSeriesDto> list = new ArrayList<>();
        String fromformat = ApiUtils.printDate(fromDate);
        String toformat = ApiUtils.printDate(toDate);
        long between = (toDate.getTime() - fromDate.getTime());
        int minutes = (int) (between / (1000 * 60));
        String desire = "RAW";
        if (minutes <= 30) {
            desire = "RAW";
        } else if (minutes > 30 && minutes < 300) {
            desire = "TEN_MINUTELY";
        } else if (minutes >= 300 && minutes < 1800) {
            desire = "HOURLY";
        } else if (minutes >= 1800 && minutes < 10800) {
            desire = "SIX_HOURLY";
        } else {
            desire = "DAILY";
        }
        System.out.println("desire" + desire);
        System.out.println("fromformat" + fromformat);
        System.out.println("toformat" + toformat);
        ApiTimeSeriesRequest atsr = new ApiTimeSeriesRequest();
        atsr.setQuery(query);
        atsr.setFrom(fromformat);
        atsr.setTo(toformat);
        atsr.setDesiredRollup(desire);
        atsr.setMustUseDesiredRollup(true);
        RootResourceV33 rootResource = getRootResource();
        TimeSeriesResourceV11 t11 = rootResource.getTimeSeriesResource();
        Response res = t11.queryTimeSeries(atsr);
        //pom依赖用systemPath则res.readEntity(String.class)报错，此处先注释
//        String jsonResponseStr = res.readEntity(String.class);
        String jsonResponseStr = "";
        JSONObject jsonResponse = JSONUtil.parseObj(jsonResponseStr);
        JSONArray jsonArray = jsonResponse.getJSONArray("items");
        if(jsonArray.size()>0){
            JSONObject jsonObject = jsonArray.getJSONObject(0);
            JSONArray timeSeries = jsonObject.getJSONArray("timeSeries");
            if(timeSeries.size()>0){
                for (int i = 0; i < timeSeries.size(); i++) {
                    TimeSeriesDto vo = new TimeSeriesDto();
                    JSONObject timeSerie = timeSeries.getJSONObject(i);
                    JSONObject metadata = timeSerie.getJSONObject("metadata");
                    JSONArray datas = timeSerie.getJSONArray("data");
                    vo.setMetricName(metadata.getStr("metricName"));
                    vo.setHostname(metadata.getJSONObject("attributes").getStr("hostname"));
                    vo.setActive(metadata.getJSONObject("attributes").getBool("active"));
                    JSONArray unitNumerators = metadata.getJSONArray("unitNumerators");
                    if(unitNumerators.size()>0){
                        String unitName = unitNumerators.get(0).toString();
                        vo.setUnit(unitName);
                    }

                    String cmdTimestamp = datas.getJSONObject(datas.size() - 1).getStr("timestamp");
                 /*
                   // 计算本地时区与 UTC 时间之间的时差
                    ZoneOffset offset = OffsetDateTime.now().getOffset();
                    // 解析 UTC 时间字符串为 OffsetDateTime 对象，并应用时差
                    OffsetDateTime utcDateTime = OffsetDateTime.parse(cmdTimestamp).withOffsetSameInstant(offset);
                    LocalDateTime localDateTime = utcDateTime.toLocalDateTime();
                    */

                    String cstTimestamp = DateUtil.format(transCMDateToNormal(cmdTimestamp), DatePattern.NORM_DATETIME_PATTERN);
                    vo.setTimeStampStr(cstTimestamp);


                    Object value = datas.getJSONObject(datas.size() - 1).getBigDecimal("value");
                    vo.setValue(value);
                    list.add(vo);
                }
            }

        }
        return list;
    }


    public static RootResourceV33 getRootResource(){
        ApiRootResource root = new ClouderaManagerClientBuilder().withHost(cdhApiPath)
                .withPort(Integer.parseInt(cdhApiPort)).withUsernamePassword(cdhApiUserName, cdhApiPassword).build();
        return root.getRootV33();
    }
    /**
     * 获取Host基础信息
     * @return
     */
    public static List<ApiHost> getHosts() {
        RootResourceV33 rootResource = getRootResource();
        HostsResourceV30 hostsResource = rootResource.getHostsResource();
        List<ApiHost> hostList = hostsResource.readHosts(DataView.SUMMARY).getHosts();
        return hostList;
    }

    /**
     * 把CM的日期转换成正常的日期 CM的时间和正常的时间格式有区别，需要转换（相差8小时）
     *
     * @param cmdatestr
     * @return
     */
    public static Date transCMDateToNormal(String cmdatestr) {
        return ApiUtils.newDateFromString(cmdatestr);
    }

    /**
     * 把正常的日期转换成CM的日期，用于传参数 CM的时间和正常的时间格式有区别，需要转换（相差8小时）
     *
     * @param date
     * @return
     */
    public static String transNormalDateToCMDate(Date date) {
        return ApiUtils.printDate(date);
    }

    public static void main(String[] args) {

    }
}
